package com.ssps.front.tenant2.utils2;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ssps.entity.UserInfo;

import org.apache.shiro.crypto.hash.SimpleHash;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.*;

/**
 * @Author: peng
 */
public class Tenant2Utils {
    private static ObjectMapper MAPPER = new ObjectMapper();

    private static Properties prop = new Properties();
    /**
     * 解析json数据
     * @param json
     * @return
     */
    public static Map<String ,String> parse(String json){
        Map<String ,String> map = new HashMap<>();
        JavaType jvt = MAPPER.getTypeFactory().constructParametricType(HashMap.class, String.class, String.class);
        try {
            Map<String, String> urMap = MAPPER.readValue(json, jvt);
            map = urMap;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }finally {
            return map;
        }

    }

    /**
     * 计算车位的综合评分
     * @param list
     * @return
     */
    public static Double getAvg(List<Integer> list){
        int sum = 0;
        for(int i = 0 ; i < list.size() ; i++){
            sum += list.get(i);
        }
        DecimalFormat df=new DecimalFormat("0.00");
        double v = sum * 1.0 / list.size();
        return Double.parseDouble(df.format(v));
    }

    public static String getMyCode(){
      return   UUID.randomUUID().toString().replace("-","").substring(0,16);
    }

    /**
     * 生成盐值
     * @return
     */
    public static String getSalt(){
        String salt = "";
        Random random = new Random();
        for(int i = 0 ; i < 4 ; i++){
            salt += random.nextInt(10);
        }
        return salt;
    }

    /**
     * 根据原始密码以及盐值，MD5 循环1024次进行密码加密
     * @param password
     * @param salt
     * @return
     */
    public static String getMD5(String password,String salt){
        SimpleHash sh = new SimpleHash("MD5", password, salt, 1024);
        String hex = sh.toHex();
        password = hex;
        return password;
    }

    /**
     *
     * @param req 请求
     * @param resp 响应
     * @param paramMap 条件
     * @return
     */
    public static String doPay(HttpServletRequest req,  HttpServletResponse resp,Map<String,Object> paramMap) throws IOException {
        /**
         * 读取配置文件
         */
        prop.load(Tenant2Utils.class.getResourceAsStream("/alipay.properties"));
        /**
         * 设置响应头，表明浏览器将其作为html
         */
        resp.setContentType("text/html;charset=" + prop.getProperty("charset"));
        AlipayClient alipayClient = new DefaultAlipayClient(prop.getProperty("gatewayUrl"), prop.getProperty("app_id"),
                prop.getProperty("merchant_private_key"), "json", prop.getProperty("charset"),
                prop.getProperty("alipay_public_key"), prop.getProperty("sign_type"));

        /**
         * 将paramMap中条件取出
         * paramMap.put("loginUserInfo", loginUserInfo);
         * paramMap.put("subject", subject);
         * paramMap.put("body", body);
         * paramMap.put("out_trade_no", out_trade_no);
         * paramMap.put("total_amount", total_amount);
         */
        UserInfo loginUserInfo = (UserInfo) paramMap.get("loginUserInfo");
        String subject = (String) paramMap.get("subject");
        String body = (String) paramMap.get("body");
        String out_trade_no = (String) paramMap.get("out_trade_no");
        String total_amount = (String) paramMap.get("total_amount");
        if (loginUserInfo != null) {
            // 设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(prop.getProperty("return_url"));
            alipayRequest.setNotifyUrl(prop.getProperty("notify_url"));
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\"," + "\"total_amount\":\""
                    + total_amount + "\"," + "\"subject\":\"" + subject + "\"," + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            String result = "";
            try {
                //使用Java发送http请求，获得响应
                result = alipayClient.pageExecute(alipayRequest).getBody();
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
//            System.out.println(result);
            return result;
        }else {
            return null;
        }
    }

    public static void main(String[] args){
        //System.out.println(getSalt());
//       System.out.println(getMD5("123456","5852"));
    }
}
